package com.wx.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wx.common.*;
import com.wx.domain.dto.AuthUserDto;
import com.wx.domain.dto.CheckUserNameDto;
import com.wx.domain.dto.UpdatePwdDto;
import com.wx.domain.dto.UserBindRoleDto;
import com.wx.entity.SysRole;
import com.wx.entity.SysUser;
import com.wx.holder.SecurityUserHolder;
import com.wx.service.SysUserRoleService;
import com.wx.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>Title:      SysUserController. </p>
 * <p>Description 用户controller </p>
 * <p>Copyright: Copyright (c) 2016</p>
 * <p>Company:     陕西天璇信息科技有限公司</p>
 *
 * @author <a href="xinglinglove1029@163.com"/>杨文生</a>
 * @since 2019/9/5 10:56
 */
@RestController
@RequestMapping(value = "/sysUser", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(tags = "用户管理", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class SysUserController{

    @Resource
    private SysUserService userService;

    @Resource
    private SysUserRoleService userRoleService;

    @Resource
    private SecurityUserHolder securityUserHolder;


    /**
     * <p>Title:	  selectUserById. </p>
     * <p>Description 根据id查询用户信息</p>
     *
     * @param id String
     * @return the wrapper
     * @Author <a href="xinglinglove1029@163.com"/>杨文生</a>
     * @CreateDate 2017 /8/17 19:04
     */
    @GetMapping("/{id}")
    @ApiOperation(notes = "根据id查询用户信息", httpMethod = "GET", value = "根据id查询用户信息")
    public Wrapper<SysUser> selectUserById(@PathVariable String id) {
        SysUser user = this.userService.selectByKey(id);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, user);
    }

    /**
     * <p>Title:	  listPage. </p>
     * <p>Description 分页查询用户列表</p>
     *
     * @param pageParam the PageParam
     * @return the wrapper
     * @Author <a href="xinglinglove1029@163.com"/>杨文生</a>
     * @CreateDate 2017 /8/17 19:04
     */
    @PostMapping(value = "/listPage")
    @ApiOperation(httpMethod = "POST", value = "分页查询用户列表")
    public Wrapper<PageInfo<SysUser>> listPage(@ApiParam(name = "user", value = "用户信息") @RequestBody PageParam<SysUser> pageParam) {
        PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
        List<SysUser> listPage = userService.queryListPage(pageParam.getParam());
        PageInfo<SysUser> pageInfo = new PageInfo<>(listPage);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, pageInfo);
    }

    @PostMapping(value = "/export")
    @ApiOperation(httpMethod = "POST", value = "导出用户列表")
    public void export(HttpServletResponse response, @ApiParam(name = "user", value = "user") @RequestBody SysUser sysUser) throws IOException {
        List<SysUser> listPage = userService.queryListPage(sysUser);
        //添加响应头信息
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("护士列表.xlsx", "UTF-8"));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        //获取数据
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        //设置背景颜色
        headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        //设置头字体
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short) 15);
        headWriteFont.setBold(true);
        headWriteCellStyle.setWriteFont(headWriteFont);
        //设置头居中
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        //内容策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        //设置 水平居中
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
        EasyExcel.write(response.getOutputStream(), SysUser.class).registerWriteHandler(horizontalCellStyleStrategy)
                .sheet("用户列表").doWrite(listPage);
    }

    /**
     * <p>Title:      getCurrentUser. </p>
     * <p>Description 获取当前用户信息</p>
     *
     * @param
     * @return current user
     * @Author <a href="xinglinglove1029@163.com"/>杨文生</a>
     * @since 2018 /2/20 14:10
     */
    @GetMapping(value = "/getCurrentUser")
    @ApiOperation(httpMethod = "GET", value = "获取当前用户信息")
    public Wrapper<AuthUserDto> getCurrentUser() {
        SecurityUser securityUser = securityUserHolder.getUser();
        AuthUserDto authUserDto = userService.getAuthUserInfo(securityUser.getUserId());
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, authUserDto);
    }


    /**
     * <p>Title:      delete. </p>
     * <p>Description 根据id删除用户</p>
     *
     * @param id the id
     * @return wrapper wrapper
     * @Author <a href="xinglinglove1029@163.com"/>杨文生</a>
     * @since 2018 /2/20 14:14
     */
    @PostMapping(value = "/delete/{id}")
    @ApiOperation(httpMethod = "POST", value = "根据id删除用户")
    public Wrapper<Integer> delete(@PathVariable String id) {
        SecurityUser securityUser = securityUserHolder.getUser();
        int result = userService.deleteUserById(id, securityUser);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, result);
    }

    /**
     * <p>Title:      enable. </p>
     * <p>Description 启用用户</p>
     *
     * @param id the id
     * @return wrapper wrapper
     * @Author <a href="xinglinglove1029@163.com"/>杨文生</a>
     * @since 2018 /2/20 14:14
     */
    @PostMapping(value = "/enable/{id}")
    @ApiOperation(httpMethod = "POST", value = "启用用户")
    public Wrapper<Integer> enable(@PathVariable String id) {
        SecurityUser securityUser = securityUserHolder.getUser();
        int result = userService.enableUserById(id, securityUser);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, result);
    }

    /**
     * <p>Title:      disable. </p>
     * <p>Description 禁用用户</p>
     *
     * @param id the id
     * @return wrapper wrapper
     * @Author <a href="xinglinglove1029@163.com"/>杨文生</a>
     * @since 2018 /2/20 14:14
     */
    @PostMapping(value = "/disable/{id}")
    @ApiOperation(httpMethod = "POST", value = "禁用用户")
    public Wrapper<Integer> disable(@PathVariable String id) {
        SecurityUser securityUser = securityUserHolder.getUser();
        int result = userService.disableUserById(id, securityUser);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, result);
    }

    /**
     * <p>Title:      modifyUser. </p>
     * <p>Description 修改用户信息</p>
     *
     * @param user the user
     * @return wrapper wrapper
     * @Author <a href="xinglinglove1029@163.com"/>杨文生</a>
     * @since 2018 /2/20 15:38
     */
    @PostMapping(value = "/modifyUser")
    @ApiOperation(httpMethod = "POST", value = "修改用户信息")
    public Wrapper<Integer> modifyUser(@ApiParam(name = "user", value = "用户信息") @RequestBody @Validated(UpdateValidate.class) SysUser user) {
        SecurityUser securityUser = securityUserHolder.getUser();
        int result = userService.modifyUser(user, securityUser);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, result);
    }

    /**
     * <p>Title:      saveUserInfo. </p>
     * <p>Description 保存用户信息</p>
     *
     * @param user the user
     * @return wrapper wrapper
     * @Author <a href="xinglinglove1029@163.com"/>杨文生</a>
     * @since 2018 /2/22 17:24
     */
    @PostMapping(value = "/saveUserInfo")
    @ApiOperation(httpMethod = "POST", value = "保存用户信息")
    public Wrapper<Integer> saveUserInfo(@ApiParam(name = "user", value = "用户信息") @RequestBody @Validated(CreateValidate.class) SysUser user) {
        SecurityUser securityUser = securityUserHolder.getUser();
        user.setCreateBy(securityUser.getUserId());
        user.setCreator(securityUser.getRealName());
        user.setUpdateBy(securityUser.getUserId());
        user.setUpdater(securityUser.getRealName());
        int result = userService.saveUserInfo(user, securityUser);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, result);
    }

    /**
     * <p>Title:      checkUserName. </p>
     * <p>Description 校验用户名唯一性</p>
     *
     * @param checkUserNameDto the check user name dto
     * @return wrapper
     * @Author <a href="xinglinglove1029@163.com"/>杨文生</a>
     * @since 2018 /2/24 17:08
     */
    @PostMapping(value = "/checkUserName")
    @ApiOperation(httpMethod = "POST", value = "校验用户名唯一性")
    public Wrapper<Boolean> checkUserName(@ApiParam(name = "checkUserNameDto", value = "用户名dto") @RequestBody @Validated() CheckUserNameDto checkUserNameDto) {
        boolean flag = false;
        String userId = checkUserNameDto.getUserId();
        String userName = checkUserNameDto.getUserName();
        Example example = new Example(SysUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userName", userName);
        if (StringUtils.isNotEmpty(userId)) {
            criteria.andNotEqualTo("id", userId);
        }
        int result = userService.selectCountByExample(example);
        if (result > 0) {
            flag = true;
        }
        return WrapMapper.ok(flag);
    }

    /**
     * <p>Title:      checkUserNo. </p>
     * <p>Description 校验工号唯一性</p>
     *
     * @param checkUserNameDto the check user name dto
     * @return wrapper
     * @Author <a href="xinglinglove1029@163.com"/>杨文生</a>
     * @since 2018 /2/24 17:08
     */
    @PostMapping(value = "/checkUserNo")
    @ApiOperation(httpMethod = "POST", value = "校验工号唯一性")
    public Wrapper<Boolean> checkUserNo(@ApiParam(name = "checkUserNo", value = "用户dto") @RequestBody @Validated() CheckUserNameDto checkUserNameDto) {
        boolean flag = false;
        String userId = checkUserNameDto.getUserId();
        String userNo = checkUserNameDto.getUserNo();
        Example example = new Example(SysUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("no", userNo);
        if (StringUtils.isNotEmpty(userId)) {
            criteria.andNotEqualTo("id", userId);
        }
        int result = userService.selectCountByExample(example);
        if (result > 0) {
            flag = true;
        }
        return WrapMapper.ok(flag);
    }

    /**
     * <p>Title:      getBindRoleListByUserId. </p>
     * <p>Description 查詢当前用户所绑定的角色信息</p>
     *
     * @param userId String
     * @return
     * @Author <a href="xinglinglove1029@163.com"/>杨文生</a>
     * @since 2019/4/11 14:35
     */
    @PostMapping(value = "/getBindRoleListByUserId/{userId}")
    @ApiOperation(httpMethod = "POST", value = "查詢当前用户所绑定的角色信息")
    public Wrapper<List<String>> getBindRoleListByUserId(@PathVariable String userId) {
        List<SysRole> bindRoleList = userRoleService.getBindRoleListByUserId(userId);
        List<String> roleIds = bindRoleList.stream().map(SysRole::getId).collect(Collectors.toList());
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, roleIds);
    }

    /**
     * <p>Title:      bindRole. </p>
     * <p>Description 用户绑定角色</p>
     *
     * @param userBindRoleDto UserBindRoleDto
     * @return Wrapper
     * @Author <a href="xinglinglove1029@163.com"/>杨文生</a>
     * @since 2019/4/11 17:23
     */
    @PostMapping(value = "/bindRole")
    @ApiOperation(httpMethod = "POST", value = "用户绑定角色")
    public Wrapper<?> bindRole(@RequestBody UserBindRoleDto userBindRoleDto) {
        userRoleService.bindRole(userBindRoleDto);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE);
    }


    /**
     * <p>Title:      modifyPassword. </p>
     * <p>Description 修改密码</p>
     *
     * @param user UpdatePwdDto
     * @return Wrapper
     * @Author <a href="xinglinglove1029@163.com"/>杨文生</a>
     * @since 2019/4/11 17:23
     */
    @PostMapping(value = "/modifyPassword")
    @ApiOperation(httpMethod = "POST", value = "修改密码")
    public Wrapper<?> modifyPassword(@RequestBody UpdatePwdDto user) {
        SecurityUser securityUser = securityUserHolder.getUser();
        userService.modifyPassword(user, securityUser);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE);
    }

    /**
     * <p>Title:      resetPassword. </p>
     * <p>Description 重置密码</p>
     *
     * @param user UpdatePwdDto
     * @return Wrapper
     * @Author <a href="xinglinglove1029@163.com"/>杨文生</a>
     * @since 2019/4/11 17:23
     */
    @PostMapping(value = "/resetPassword")
    @ApiOperation(httpMethod = "POST", value = "重置密码")
    public Wrapper<?> resetPassword(@RequestBody UpdatePwdDto user) {
        SecurityUser securityUser = securityUserHolder.getUser();
        userService.resetPassword(user, securityUser);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE);
    }
}
